﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Ext.Net;
using Sio.Mdm.Client;
using Sio.Mdm.Entities;
using Sio.Mdm.BF.Ldap;
using Sio.Mdm.BF.Administracija;
using Sio.Mdm.Types.Database;
using Sio.Mdm.Types;
using Sio.Mdm.Connector;

namespace Sio.Mdm.Web.Instalacija
{
    public partial class LdapSkupineUvoz : Controls.Page
    {        
        #region Properties
        int WizardPageNumber {
            get {
                if (Session["__WizardPageNumber"] == null) return 0;
                return Int32.Parse(Session["__WizardPageNumber"].ToString());
            }
            set {
                Session["__WizardPageNumber"] = value;
            }        
        }
        
        int OrgarnizacijaID
        {
            get
            {
                if (String.IsNullOrEmpty(cmbOrgarnizacije.SelectedItem.Value)) return 0;
                return Convert.ToInt32(cmbOrgarnizacije.SelectedItem.Value); //Request.GetValue<int>("OrgarnizacijaID");
            }
        }
        #endregion

        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack && !X.IsAjaxRequest)
            {
                WizardPageNumber = 0;
                LoadOrgarnizacije();
            }                        
        }

        #region Private
        private void LoadOrgarnizacije()
        {
            EntityCollection<Sio.Mdm.Types.Database.Organizacija> orgarnizacije = new EntityCollection<Sio.Mdm.Types.Database.Organizacija>(
                  new Filter<Sio.Mdm.Types.Database.Organizacija>().Where(o => o.OrganizacijaId != null).OrderBy(o => o.Naziv));
            StoreOrgarnizacije.DataSource = orgarnizacije;
            StoreOrgarnizacije.DataBind();
        }

        private void LoadStrezniki()
        {
            string warning = "";

            if (String.IsNullOrEmpty(cmbOrgarnizacije.SelectedItem.Value))
            {
                return;
            }
            
            EntityCollection<LdapStreznik> strezniki = new EntityCollection<LdapStreznik>(
                  new Filter<LdapStreznik>().Where(o => o.OrgarnizacijaID == OrgarnizacijaID).OrderBy(o => o.Ime));
            StoreStrezniki.DataSource = strezniki;
            StoreStrezniki.DataBind();

            if (strezniki.Count == 0) warning += " Na organizaciji še ni definiranih strežnikov!";            

            lblWarning.Text = warning;
            if (!String.IsNullOrEmpty(warning))
                lblWarning.Show();
            else
                lblWarning.Hide();
        }        

        private bool CheckFields()
        { 
            if (String.IsNullOrEmpty(cmbStreznik.SelectedItem.Value.ToString())) {
                StatusBar1.SetStatus(new StatusBarStatusConfig("Napaka: strežnik ni izbran.",""));
                return false;
            }
            if (String.IsNullOrEmpty(txtDN.Text)) {
                StatusBar1.SetStatus(new StatusBarStatusConfig("Napaka: DN za imenik ni podana.",""));
                return false;
            }

            return true;
        }

        private void SetWizardButtons() {
            btnNext.Disabled = (WizardPageNumber == 3 || WizardPageNumber == 4);
            btnPrevious.Disabled = (WizardPageNumber == 0 || WizardPageNumber == 3);

            StatusBar1.SetStatus(new StatusBarStatusConfig("Posodobljeno: " + DateTime.Now.ToLongTimeString() + " (server time)", ""));
        }

        private bool GetLdapADGroups()
        {
            int existingGroups = 0;
            int newGroups = 0;
            // Get data from Ldap/AD server            
            int streznik = Convert.ToInt32(cmbStreznik.SelectedItem.Value);

            var slServiceLdap = ServiceFactory.GetService<ILdapService>();
            List<ldapObject> groups = null;
            Result result = slServiceLdap.GetLdapADGroups(streznik, txtDN.Text, out groups, this.UserSession);
            
            if (result != null)
            {
                lblError.Text = result.Message;
                return false;
            }

            // (2) Get current groups for this server        
            EntityCollection<LdapSkupinaStoritev> skupine = new EntityCollection<LdapSkupinaStoritev>(
                new Filter<LdapSkupinaStoritev>().Where(r => r.StoritevKljuc == streznik));

            List<string> currentkeys = new List<string>();
            foreach (LdapSkupinaStoritev skupina in skupine)
            {
                currentkeys.Add(skupina.StoritevParam);
            }

            // (3) Prepare data for STORE
            List<LdapGroup> list = new List<LdapGroup>();            
            foreach (ldapObject group in groups)
            {
                if (!currentkeys.Contains(group.DN))
                {
                    LdapGroup g = new LdapGroup(group.CN, group.DN);
                    if (group["description"] != null) g.Description = group["description"][0].ToString();
                    list.Add(g);
                    newGroups++;
                }
                else {
                    existingGroups++;   
                }
            }

            var tmpArray = (from l in list orderby l.CN select new Object[3] { l.CN, l.DN, l.Description });
            StoreSkupineSeznam.DataSource = tmpArray;
            StoreSkupineSeznam.DataBind();

            // (4) Prepare infp page
            lblInfo.Html = String.Format("Število vseh skupin na strežniku je: {0} <br><br>Število že obstoječih skupin v SIO.MDM: {1} <br><br>Število skupin na voljo za uvoz: {2} <br><br>", groups.Count, existingGroups, newGroups);
            lblInfo2.Hidden = newGroups!=0;                

            return true;
        }

        private bool SaveLdapADGroups(List<string> dnList)
        {
            Result result;
            var slServiceLdap = ServiceFactory.GetService<ILdapService>();
            int streznik = Convert.ToInt32(cmbStreznik.SelectedItem.Value);
            int saved = 0;

            foreach (string dn in dnList)
            {
                result = slServiceLdap.SaveLdapADGroup(streznik, txtDN.Text, dn, this.UserSession);                
                if (result!=null) {
                    return false;
                }
                saved++;
            }

            lblSuccess.Html = String.Format("Število uspešno uvoženih skupin: {0}.", saved);

            return true;
        }
       
        #endregion

        #region Protected
        protected void ButtonClicked(object sender, DirectEventArgs e)
        {

        }

        [DirectMethod]
        protected void PreviousClicked(object sender, DirectEventArgs e)
        {
            if (WizardPageNumber == 4)
                WizardPageNumber = 0;
            else
                WizardPageNumber--;

            if (WizardPageNumber < 0) WizardPageNumber = 0;

            PanelMain.ActiveIndex = WizardPageNumber;
            SetWizardButtons();
        }

        [DirectMethod]
        protected void NextClicked(object sender, DirectEventArgs e)
        {
            // CHECK
            if (WizardPageNumber == 0)
            {
                SetWizardButtons();
                if (!CheckFields()) return;
            }

            WizardPageNumber++;

            if (WizardPageNumber == 1)
            {
                if (!GetLdapADGroups())
                {
                    WizardPageNumber = 4;             // Error Page
                }
            }

            if (WizardPageNumber == 3)
            {
                List<string> selectedItems = e.GetIdList<string>("selected", "DN");
                if (!SaveLdapADGroups(selectedItems))
                {
                    WizardPageNumber = 4;           // Error Page
                }
            }

            PanelMain.ActiveIndex = WizardPageNumber;

            SetWizardButtons();

            return;
        }

        [DirectMethod]
        protected void OnOrgarnizacijaChanged(object sender, DirectEventArgs e)
        {
            LoadStrezniki();
        }
        #endregion

        #region Class LdapGroup
        private class LdapGroup
        {            
            public string DN="";
            public string CN="";
            public string Description="";

            public LdapGroup(string cn, string dn) 
            {                
                this.DN = dn;
                this.CN = cn;
            }
        }
        #endregion
    }    
}
